package com.ruoyi.system.controller;

import com.ruoyi.system.dto.FileDto;
import com.ruoyi.system.service.MinioService;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system/minio")
public class MinioController {

    @Autowired
    private MinioService minioService;

    // 上传文件
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        minioService.uploadFile(file.getOriginalFilename(), file.getInputStream(), file.getSize());
        return "File uploaded successfully.";
    }

    // 下载文件
    @GetMapping("/download/{fileName}")
    public ResponseEntity<InputStreamResource> download(@PathVariable String fileName) throws Exception {
        InputStream inputStream = minioService.downloadFile(fileName);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(new InputStreamResource(inputStream));
    }

    // 删除文件
    @DeleteMapping("/delete/{fileName}")
    public String delete(@PathVariable String fileName) throws Exception {
        minioService.deleteFile(fileName);
        return "File deleted successfully.";
    }

    // 列出文件
    @GetMapping("/list")
    public List<FileDto> listFiles() throws Exception {
        List<Item> items = minioService.listFiles();
        List<FileDto> fileDtos = new ArrayList<>();

        for (Item item : items) {

            String fileUrl = "http://192.168.20.6:59000/test1/" + item.objectName();
            fileDtos.add(new FileDto(item.objectName(), fileUrl));
        }

        return fileDtos;
    }
}

